<?php
namespace Admin\Controller;
use Think\Controller;
class LoginController extends Controller {
	//代理注册
    public function register(){
        $this->display();
    }
    //判断该手机号代理是否已存在
    public function checkPhone(){
        $uOb=M('Admin');
        $phone=I('phone');
        $re=$uOb->where("phone='".$phone."'")->find();
        if ($re && $re['admin_id']) {
            $this->ajaxReturn('exist');
        }else{
            $this->ajaxReturn('success');
        }
    }
    //代理注册数据保存
    public function registerSave(){
        $data=I('post.');
        $aOb=M('Admin');
        //判断身份证号是否已存在
        if ($data['id_no']) {
            $id_exist=$aOb->field('admin_id')->where('id_no="'.$data['id_no'].'"')->find();
            if ($id_exist) {
                $this->ajaxReturn('id_exist');
            }
        }
        //判断推荐码是否已存在
        if ($data['p_code']) {
            $pid=$aOb->field('admin_id,node_id')->where('code='.$data['p_code'])->find();
            if ($pid) {
                $data['pid']=$pid['admin_id'];
                $data['node_id']=$pid['node_id'].$pid['admin_id'].'|';
            }else{
                $this->ajaxReturn('code_nexist');
            }
        }
        //判断手机号是否已存在
        if ($data['phone']) {
            $phone_exist=$aOb->field('admin_id')->where('phone="'.$data['phone'].'"')->find();
            if ($phone_exist) {
                $this->ajaxReturn('phone_exist');
            }
        }
        if (session('code') && session('expire')<time()) {
            $this->ajaxReturn('past');
        }else if($data['code']==session('code') && $data['phone']==session('phone')){
            $last_code=$aOb->field('code')->where('role=1')->order('admin_id desc')->find();
            if ($last_code) {
                $data['code']=$last_code['code']+1;
            }else{
                $data['code']=10001;
            }
            $data['addtime']=time();
            $data['password']=md5($data['password']);
            $re=$aOb->add($data);
            if ($re) {
                $this->ajaxReturn('success');
            }else{
                $this->ajaxReturn('false');
            }
        }else{
            $this->ajaxReturn('code_error');
        }
        
    }
    //登录页面
    public function login(){
        $phone=I('get.phone');
        if (I('get.errorTips')=='error') {
            $errorTips='账号或密码错误！';
        }
        if (I('get.errorTips')=='blacklist') {
            $errorTips='对不起，您的账号已被封停，请联系管理员！';
        }
        $this->assign('phone',$phone);
        $this->assign('errorTips',$errorTips);
        $this->display();
    }
   
    //登录验证
    function check(){
		$phone=I('phone');
		$password=md5(I('password'));
		$adminOb=M('Admin');
		$re=$adminOb->field('admin_id,phone,code,truename,status,role')->where("phone='{$phone}' and password='{$password}'")->find();
        // var_dump($re);die;
		if ($re) {
            if ($re['status']==1) {
                header("location:" . U('Admin/Login/login',array('phone'=>$phone,'errorTips'=>'blacklist')));
            }else{
                if (!$re['truename']) {
                    $re['truename']=$re['phone'];
                }
                session('gm_admin',$re);  
                session('adminid',$re['admin_id']);  
                header("location:" . U('Admin/Index/index'));
            }
		}else{
            header("location:" . U('Admin/Login/login',array('phone'=>$phone,'errorTips'=>'error')));
		}
	}

	//退出登录
	function out(){
		session('gm_admin',null);
        header("location:" . U('Admin/Login/login'));
	}
    //发送手机验证码
    public function getCode(){
        $phone=I('post.phone');
        //判断手机号是否已存在
        $phone_exist=M('Admin')->field('admin_id')->where('phone="'.$phone.'"')->find();
        if ($phone_exist) {
            $this->ajaxReturn('phone_exist');
        }
        //不存在，调短信接口
        $re=$this->getMsgCode($phone);
        $this->ajaxReturn($re);
    }
    /**
    *手机号登录，调第三方接口获取验证码
    *@param $phone int 用户手机号
    *@return array('code'=>200/201,
     *                          'status'=>success/false,
     *                          'message'=>'成功/失败/超时')
    */
    public function getMsgCode($phone){         
        $code=rand(1000,9999);
        //引入第三方库，并且将文件名改为原文件名.class.php的形式
        import('Org.Alidayu.top.TopClient');
        import('Org.Alidayu.top.ResultSet');
        import('Org.Alidayu.top.RequestCheckUtil');
        import('Org.Alidayu.top.TopLogger');
        import('Org.Alidayu.top.request.AlibabaAliqinFcSmsNumSendRequest');     
        $c = new \TopClient;
        $c->appkey = C('APPKEY');
        $c->secretKey = C('SECRET');
        $req = new \AlibabaAliqinFcSmsNumSendRequest;
        // $req->setExtend("123456");//确定发给的是哪个用户，参数为用户id
        $req->setSmsType("normal");
        $req->setSmsFreeSignName(C('SIGN_NAME'));
        $req->setSmsParam("{'number':'".$code."','product':'".C('PRODUCT')."'}");
        //这里设定的是发送的短信内容：验证码${number}，您正在进行${product}身份验证，打死不要告诉别人哦！”,阿里大鱼管理后台添加短信模板内容，此两个为替换模板中参数
        $req->setRecNum($phone);//参数为用户的手机号码
        $req->setSmsTemplateCode(C('MSG_TMP_ID'));//短信模板id
        $resp = $c->execute($req);
        // var_dump($resp);
        //验证码发送成功，将验证码相关数据写进数据库
        if ($resp->code==0) {  
                if(session('code')){
                   session('code',null); 
                   session('expire',null); 
                }
                 session('phone',$phone);
                 session('code',$code);
                 session('expire',time()+130);//验证码过期时间2分钟
            $data='success';
        }else if ($resp->sub_code=='isv.BUSINESS_LIMIT_CONTROL') {
            $data='outtimes';
        }else{
            $data='false';
        } 
        return $data;
    }
}